import time
import BaseHTTPServer, cgi
import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler
import json
from DBConnection import DBConn


HOST_NAME = '172.30.242.233' # !!!REMEMBER TO CHANGE THIS!!!
PORT_NUMBER = 9000 # Maybe set this to 9000.
CONNECTION = DBConn()

class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_HEAD(s):
        s.send_response(200)
        s.send_header("Content-type", "text/html")
        s.end_headers()
    def do_GET(s):
        """Respond to a GET request."""
        if s.path.startswith("/getaccessbyaccessid"):
            s.send_response(200)
            s.send_header("Content-type", "application/json")
            s.end_headers();
            
            par = urlparse.parse_qs(urlparse.urlparse(s.path).query)
            
            #print(par['accessid'][0])
            
            access = CONNECTION.get_access_by_accessid(par['accessid'][0], par['doorid'][0])
            print(access);
            
            Access = {'Access':'' + access + ''}
            
            response = json.dumps(Access);
            
            s.wfile.write(response)
        if s.path == "/getusers":
            s.send_response(200)
            s.send_header("Content-type", "application/json")
            s.end_headers()

            users = CONNECTION.get_users()
            print(users)
            JSONusers = []
            for User in users:
                #Create JSON list 
                JSONusers.append({"id": User[0], "accessid": User[1], "name": User[2]})
                print User
            print json.dumps(JSONusers)
            # Pack the JSON list in a JSON object
            s.wfile.write("{\"users\":" + json.dumps(JSONusers) + "}")
        if s.path == "/getdoors":
            s.send_response(200)
            s.send_header("Content-type", "application/json")
            s.end_headers()

            doors = CONNECTION.get_doors()
            print(doors)
            JSONdoors = []
            for Door in doors:
                #Create JSON list 
                JSONdoors.append({"id": Door[0], "doorInfo": Door[1]})
                print Door
            print json.dumps(JSONdoors)
            # Pack the JSON list in a JSON object
            s.wfile.write("{\"doors\":" + json.dumps(JSONdoors) + "}")
        # Here we have to use something like .startswith();
        if s.path.startswith("/getuseraccessbydoorid"):
            s.send_response(200)
            s.send_header("Content-type", "application/json")
            s.end_headers()
            
            users = CONNECTION.get_users_and_access(s.path.lstrip('/getuseraccessbydoorid/'))
            print(users)
            JSONusers_access = []
            for User in users:
                #Create JSON list 
                JSONusers_access.append({"id": User[0], "name": User[1], "accessid": User[2], "access": User[3]})
                print User
            print json.dumps(JSONusers_access)
            # Pack the JSON list in a JSON object
            s.wfile.write("{\"useraccess\":" + json.dumps(JSONusers_access) + "}")
        if s.path.startswith("/getdooraccessbyuserid"):
            s.send_response(200)
            s.send_header("Content-type", "application/json")
            s.end_headers()
            
            doors = CONNECTION.get_doors_and_access(s.path.lstrip('/getdooraccessbyuserid/'))
            print(doors)
            JSONdoors_access = []
            for Door in doors:
                #Create JSON list 
                JSONdoors_access.append({"id": Door[0], "info": Door[1], "access": Door[2]})
                print Door
            print json.dumps(JSONdoors_access)
            # Pack the JSON list in a JSON object
            s.wfile.write("{\"dooraccess\":" + json.dumps(JSONdoors_access) + "}")
        # If someone went to "http://something.somewhere.net/foo/bar/",
        # then s.path equals "/foo/bar/".
    def do_POST(s):
        print(s.path)
        """Respond to POST request"""
        if s.path == "/adduserdooraccess":
            
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))
            s.send_response(200)
            s.end_headers()

            data = json.loads(s.data_string)
            
            CONNECTION.set_user_door_access(data['userid'], data['doorid'])
            
            s.wfile.write("Success!");
        if s.path == "/deleteuserdooraccess":
            
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))
            s.send_response(200)
            s.end_headers()

            data = json.loads(s.data_string)
            
            CONNECTION.remove_user_door_access(data['userid'], data['doorid'])
            
            s.wfile.write("Success!");
        if s.path == "/changedoorinfo":
            
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))
            s.send_response(200)
            s.end_headers()

            data = json.loads(s.data_string)
            
            CONNECTION.change_door_info(data['doorid'], data['doorinfo'])
            
            s.wfile.write("Success!");
        if s.path == "/changeusername":
            
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))
            s.send_response(200)
            s.end_headers()

            data = json.loads(s.data_string)
            
            CONNECTION.change_user_name(data['userid'], data['username'])
            
            s.wfile.write("Success!");
        if s.path == "/changeuseraccessid":
            
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))
            s.send_response(200)
            s.end_headers()

            data = json.loads(s.data_string)
            
            CONNECTION.change_user_accessid(data['userid'], data['useraccessid'])
            
            s.wfile.write("Success!");
        if s.path == "/createdoor":
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))
            s.send_response(200)
            s.end_headers()

            data = json.loads(s.data_string)
            
            CONNECTION.create_door(data['info'], data['users'])
            
            s.wfile.write("Success!");
        if s.path == "/createuser":
            # Parse the form data posted
            s.data_string = s.rfile.read(int(s.headers['Content-Length']))

            data = json.loads(s.data_string)
            
            success = CONNECTION.create_user(data['name'], data['accessid'], data['doors'])
            
            if success == True:
                s.send_response(200)
                s.end_headers()
                s.wfile.write("Success!");
            else:
                s.send_response(400)
                s.end_headers()
                s.wfile.write("Error!");
        if s.path.startswith("/deletedoor"):
            
            s.send_response(200)
            s.end_headers()
            
            CONNECTION.delete_door(s.path.lstrip('/deletedoor/'))
            
            s.wfile.write("Success!");
        if s.path.startswith("/deleteoneuser"):
            
            s.send_response(200)
            s.end_headers()
            
            CONNECTION.delete_user(s.path.lstrip('/deleteoneuser/'))
            
            s.wfile.write("Success!");
if __name__ == '__main__':
    server_class = BaseHTTPServer.HTTPServer
    httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
    print time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
    CONNECTION.close()
    print time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER)